package com.rh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rh.controller.front.vo.CourseFrontVo;
import com.rh.controller.front.vo.CourseWebVo;
import com.rh.entity.EduCourse;
import com.rh.entity.EduCourseDescription;
import com.rh.entity.vo.CoursePageVo;
import com.rh.entity.vo.CoursePublishVo;
import com.rh.entity.vo.CourseVo;
import com.rh.exception.EducationException;
import com.rh.mapper.EduCourseMapper;
import com.rh.service.EduChapterService;
import com.rh.service.EduCourseDescriptionService;
import com.rh.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rh.service.EduVideoService;
import com.rh.result.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程 服务实现类
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    //注入EduCourseDescriptionService为了添加到edu_course_description表
    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private EduChapterService chapterService;

    //添加课程信息
    @Override
    public String saveCourseInfo(CourseVo courseVo) {
        //向课程表中添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        //把courseVo对象复制到eduCourse中
        BeanUtils.copyProperties(courseVo,eduCourse);
        //添加到edu_course表
        int insert = baseMapper.insert(eduCourse);
        if(insert<=0){
            //添加失败
            throw new EducationException(20001,"添加课程信息失败");
        }
        //
        //添加到edu_course_description
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        //它只有两个字段1个课程详情1个课程id
        eduCourseDescription.setDescription(courseVo.getDescription());
        //这里的id必须是EduCourse实体类中获取出来的id
        eduCourseDescription.setId(eduCourse.getId());
        boolean save = eduCourseDescriptionService.save(eduCourseDescription);
        if (save==false){
            throw new EducationException(20002,"添加课程详情信息失败");
        }
        //返回一个课程id用于前端课程大纲和章节的擦欧总
        return eduCourse.getId();
    }

    /**
     * 根据课程ID查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseVo getCourseInfo(String courseId) {
        //1.查询课程列表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        //2.查询课程描述
        EduCourseDescription eduCourseDescription = eduCourseDescriptionService.getById(courseId);
        //3.把这两个数据封装到courseVo中
        CourseVo courseVo = new CourseVo();
        //设置课程描述
        courseVo.setDescription(eduCourseDescription.getDescription());
        //封装数据
        BeanUtils.copyProperties(eduCourse,courseVo);
        return courseVo;
    }

    /**
     * 修改课程信息
     * @param courseVo
     */
    @Override
    public void updateCouseInfo(CourseVo courseVo) {
        //1.修改课程表
        EduCourse eduCourse = new EduCourse();
        //把入参vo的值复制到eduCourse中
        BeanUtils.copyProperties(courseVo,eduCourse);
        int i = baseMapper.updateById(eduCourse);
        if(i<=0){
            throw new EducationException(20001,"修改课程信息失败");
        }
        //2.修改课程简介表
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(courseVo.getId());
        eduCourseDescription.setDescription(courseVo.getDescription());
        boolean b = eduCourseDescriptionService.updateById(eduCourseDescription);
        if(!b){
            throw new EducationException(20001,"修改课程信息失败");
        }
    }

    /**
     * 根据课程id查询最终课程基本信息
     * @param id
     * @return
     */
    @Override
    public CoursePublishVo getPublishCourse(String id) {
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;
    }

    /**
     * 条件查询带分页获取课程列表
     * @param current
     * @param limit
     * @param coursePageVo
     * @return
     */
    @Override
    public ResultVo pageQuery(Long current, Long limit, CoursePageVo coursePageVo) {
        //构造分页对象
        Page<EduCourse> coursePage=new Page<>();
        //构造条件构造器
        QueryWrapper<EduCourse> wrapper =new QueryWrapper<>();
        //如果coursePageVo为空就调用分页方法
        if(coursePageVo==null){
            return this.findCoursePage(current,limit);
        }
        String title=coursePageVo.getTitle();
        String status=coursePageVo.getStatus();
        String subjectParentId = coursePageVo.getSubjectParentId();
        String subjectId = coursePageVo.getSubjectId();
        String teacherId = coursePageVo.getTeacherId();
        //做校验
        if(!StringUtils.isEmpty(title)){
            wrapper.like("title",title);
        }
        if(!StringUtils.isEmpty(teacherId)){
            wrapper.eq("teacher_id",teacherId);
        }
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(subjectId)){
            wrapper.eq("subject_id", subjectId);
        }
        if(!StringUtils.isEmpty(subjectParentId)){
            wrapper.eq("subject_parent_id", subjectParentId);
        }
        //根据添加时间排序
        wrapper.orderByDesc("gmt_create");
        //调用Mapper里面的方法
        baseMapper.selectPage(coursePage,wrapper);
        //总数
        long total = coursePage.getTotal();
        //总数据
        List<EduCourse> records = coursePage.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",records);
        return ResultVo.ok().data(map);
    }

    /**
     * 分页查询
     * @param current
     * @param limit
     * @return
     */
    @Override
    public ResultVo findCoursePage(Long current, Long limit) {
        //创建分页构造器
        Page<EduCourse>coursePage=new Page<>(current,limit);
        IPage<EduCourse> eduCourseIPage = baseMapper.selectPage(coursePage, null);
        long total = coursePage.getTotal();
        List<EduCourse> records = coursePage.getRecords();
        Map<String,Object> map=new HashMap<>();
        map.put("total",total);
        map.put("rows",records);
        return ResultVo.ok().data(map);
    }

    /**
     * 删除课程信息
     * @param courseId
     */
    @Override
    public void removeCourse(String courseId) {
        //1.根据课程id删除小节
       eduVideoService.removeVideoByCourseId(courseId);
       //2.根据课程id删除章节
       chapterService.removeChapterByCourseId(courseId);
       //3.根据课程id删除描述
       eduCourseDescriptionService.removeById(courseId);
       //4.根据课程id删除课程本身
        int i = baseMapper.deleteById(courseId);
        if(i==0){
            throw new EducationException(20001,"删除失败!");
        }


    }

    /**
     * 查询课程数据
     * 添加到缓存key名 banner::selectIndexCourseList
     * @return
     */
    @Cacheable(value = "banner",key = "'selectIndexCourseList'")
    @Override
    public List<EduCourse> courseList() {
        //课程数据
        QueryWrapper<EduCourse> eduCourseQueryWrapper = new QueryWrapper<>();
        eduCourseQueryWrapper.orderByDesc("id");
        eduCourseQueryWrapper.last("limit 8");
        List<EduCourse> eduCourseListlist = baseMapper.selectList(eduCourseQueryWrapper);
        return eduCourseListlist;
    }

    /**
     * 课程前台条件查询带分页
     * @param coursePage
     * @param courseFrontVo
     * @return
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> coursePage, CourseFrontVo courseFrontVo) {
        //参数校验
        String title = null;
        String subjectId = null;
        String subjectParentId = null;
        String gmtCreateSort = null;
        String buyCountSort = null;
        String priceSort = null;
        String teacherId = null;
        if (!StringUtils.isEmpty(courseFrontVo)){
            title = courseFrontVo.getTitle();
            subjectId = courseFrontVo.getSubjectId();
            subjectParentId = courseFrontVo.getSubjectParentId();
            gmtCreateSort = courseFrontVo.getGmtCreateSort();
            buyCountSort = courseFrontVo.getBuyCountSort();
            priceSort = courseFrontVo.getPriceSort();
            teacherId = courseFrontVo.getTeacherId();
        }
        //构造mybatisplus查询对象
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空,不为空就拼接
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())){//一级分类不为空
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())){//二级分类不为空
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())){//购买量不为空,降序排列
            wrapper.orderByDesc("buy_count");
        }
        if(!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())){//最新时间排序不为空,降序排列
            wrapper.orderByDesc("gmt_create");
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())){//购买量不为空,降序排列
            wrapper.orderByDesc("price");
        }
        //调用方法得到数据
        baseMapper.selectPage(coursePage,wrapper);
        //创建一个Map集合封装分页数据
        Map<String,Object>map=new HashMap<>();

        //数据的list集合
        List<EduCourse> records = coursePage.getRecords();
        //当前页
        long current = coursePage.getCurrent();
        //总页数
        long pages1 = coursePage.getPages();
        //每页记录数
        long size = coursePage.getSize();
        //总记录数
        long total = coursePage.getTotal();

        //是否有上一页
        boolean hasPrevious = coursePage.hasPrevious();
        //是否有下一页
        boolean hasNext = coursePage.hasNext();

        //封装参数
        map.put("items",records);
        map.put("current",current);
        map.put("pages",pages1);
        map.put("size",size);
        map.put("total",total);
        map.put("hasPrevious",hasPrevious);
        map.put("hasNext",hasNext);

        return map;
    }

    /**
     *  //课程前台,根据课程id查询基本信息
     * @param courseId
     */
    @Override
    public CourseWebVo getBaseCourseFrontInfo(String courseId) {
        return baseMapper.getBaseCourseFrontInfo(courseId);
    }
}
